package com.sheledon.flyCat.network.socket.resolver;

import com.sheledon.flyCat.network.socket.http.enum_.HttpMethod;
import com.sheledon.flyCat.network.socket.http.HttpRequest;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Objects;

/**
 * @author sheledon
 */
public class HttpResolver {
    private static final int BUFFER_SIZE = 1024*10;
    public static HttpRequest resolve(InputStream inputStream) throws IOException {
        BufferedReader reader =new BufferedReader(new InputStreamReader(inputStream));
        HttpRequest httpRequest = new HttpRequest();
        String str ;
        //跳开空格
        while ((str= reader.readLine())==null || str.length()==0){ }
        parseRequestLine(str,httpRequest);
        parseRequestHeader(reader,httpRequest);
        if (HttpMethod.POST.equals(httpRequest.getMethod())){
            getRequestBody(reader,httpRequest);
        }
        return httpRequest;
    }
    private static void parseRequestLine(String str,HttpRequest request){
        String [] splits = str.split("\\s+");
        System.out.println(str);
        if (splits.length<3){
            //bad request
            return;
        }
        if ("get".equals(splits[0])|| "GET".equals(splits[0])){
            request.setMethod(HttpMethod.GET);
        }else if ("post".equals(splits[0])|| "POST".equals(splits[0])){
            request.setMethod(HttpMethod.POST);
        }else{
            // bad request
        }
        // parse url include(uri and parameters)
        parseRequestUri(splits[1],request);
        request.setVersion(splits[2]);
    }
    private static void parseRequestUri(String uri, HttpRequest request){
        String[] split = uri.split("\\?");
        if (split.length==0){
            //bad request
        }
        request.setUrl(split[0]);
        if (split.length==2){
            HashMap<String,String> parMap = new HashMap<>();
            String [] parameters = split[1].split("&");
            for (String p : parameters){
                int sp = p.lastIndexOf("=");
                String key = p.substring(0,sp);
                String value = p.substring(sp+1);
                parMap.put(key,value);
            }
            request.setRequestParams(parMap);
        }
    }
    private static void parseRequestHeader(BufferedReader reader, HttpRequest request) throws IOException {
        HashMap<String,String> headers = new HashMap<>();
        String str ;
        while((str=reader.readLine())!=null&&str.length()!=0){
            System.out.println(str);
            String [] split = str.split(":");
            if (split.length==2){
                headers.put(split[0].trim(),split[1].trim());
            }
        }
        request.setRequestHeaders(headers);
    }
    //暂时实现解析json格式,后面扩展
    private static void getRequestBody(BufferedReader reader, HttpRequest request){
        char [] cbuffer = new char[BUFFER_SIZE];
        StringBuilder builder = new StringBuilder();
        int len ;
        String contentLengthStr =request.getRequestHeaders().get("Content-Length");
        int contentLength = Objects.isNull(contentLengthStr) ? 0 : Integer.parseInt(contentLengthStr);
        int total = 0;
        try {
            while (total!=contentLength){
                len = reader.read(cbuffer);
                total+=len;
                builder.append(cbuffer,0,len);
            }
            request.setBody(builder.toString());
        }catch (Exception e){}
    }
}
